﻿using HsServerHa.Common;
using HsServerHa.Common.Auth;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.NetWork;
using HsServerHa.Utility.SQLite;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HsServerHa.Jobs
{
    /// <summary>
    /// 循环检测任务
    /// 用来检测本机是否配置心跳，全局配置，如果有就尝试跳动
    /// 朱润来
    /// 2023年10月12日08:51:37
    /// </summary>

    /// <summary>
    /// 该属性告诉Quartz不要同时执行给定Job定义
    /// </summary>
    [DisallowConcurrentExecution]
    public class RecurringTaskJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                return;
            }

            #endregion
            try
            {
                //LoggerHelper.Info("开始循环检测任务");

                await PingGateway();
                await PingReferIP();
                await PingVirtuallyIP();
                await InitiateHeart();
                await RemoveLog();
                 

            }
            catch (Exception ex)
            {
                LoggerHelper.Error(ex.Message);
                LoggerHelper.Error(ex.StackTrace);
            }
        
        }

        /// <summary>
        /// Ping网关IP
        /// 2023年10月12日09:25:18
        /// </summary>
        public async Task PingGateway()
        {
            var ip = App.GatewayIP;
            if (NetWorkHelper.ValidateIpAddress(ip))
            {
                var isSuccess = NetWorkHelper.IsPingIP(ip);
                if (isSuccess)
                {
                    App.IsPingGateway = true;
                    //LoggerHelper.Info("Ping网关IP成功");
                }
                else
                {
                    App.proxSocket = null;
                    App.socketServer = null;
                    App.IsPingGateway = false;
                    LoggerHelper.Error("Ping网关IP失败");
                }
            }
        }


        /// <summary>
        /// Ping参考IP
        /// 朱润来
        /// 2023年10月12日09:25:15
        /// </summary>
        public async Task PingReferIP()
        {
            var ip = App.ReferIP;
            if (NetWorkHelper.ValidateIpAddress(ip))
            {
                var isSuccess = NetWorkHelper.IsPingIP(ip);
                if (isSuccess)
                {
                    App.IsPingRefer = true;
                    //LoggerHelper.Info("Ping参考IP成功");
                }
                else
                {
                    App.proxSocket = null;
                    App.socketServer = null;
                    App.IsPingRefer = false;
                    LoggerHelper.Error("Ping参考IP失败");
                }
            }
        }

        /// <summary>
        /// Ping参考IP
        /// 朱润来
        /// 2023年10月12日09:25:15
        /// </summary>
        public async Task PingVirtuallyIP()
        {
            var ip = App.VirtuallyIP;
            if (NetWorkHelper.ValidateIpAddress(ip))
            {
                var isSuccess = NetWorkHelper.IsPingIP(ip);
                if (isSuccess)
                {
                    App.IsPingVirtuallyIP = true;
                    //LoggerHelper.Info("Ping虚拟IP成功");
                }
                else
                {
                    App.IsPingVirtuallyIP = false;
                    LoggerHelper.Error("Ping虚拟IP失败");
                }
            }
        }


        public static UdpClient client = new UdpClient(8080);
        public static IPEndPoint point;

        public static CancellationTokenSource source = new CancellationTokenSource();
        public static bool isRunning = false;

        public async Task InitiateHeart()
        {
            try
            {
                if (App.proxSocket == null)
                {
                    App.StartSocket();

                    if (App.isMaster != null)
                    {
                        if (!App.isMaster.Value)
                        {
                            if (!string.IsNullOrEmpty(App.MasterIP) && !string.IsNullOrEmpty(App.XtIP))
                            {
                                App.XtDisconnectNum += 1;
                                Thread.Sleep(1000);
                            }

                        }
                    }
                    App.XtIsOpen = false;

                    return;
                }
                else
                {
                    if (!App.proxSocket.Connected)
                    {
                        App.StartSocket();

                        if (App.isMaster != null)
                        {
                            if (!App.isMaster.Value)
                            {
                                if (!string.IsNullOrEmpty(App.MasterIP) && !string.IsNullOrEmpty(App.XtIP))
                                {
                                    App.XtDisconnectNum += 1;
                                    Thread.Sleep(1000);
                                }

                            }
                        }
                        App.XtIsOpen = false;

                        return;
                    }
                }
                if (App.proxSocket.Connected)
                {
                    if (App.isMaster != null)
                    {
                        if (!App.isMaster.Value)
                        {
                            if (!NetWorkHelper.IsPingIP(App.MasterIP))
                            {
                                App.proxSocket = null;
                                App.socketServer = null;
                            }
                        }
                    }

                    if (App.proxSocket == null)
                    {
                        return;
                    }
                    if (!App.isMaster.Value)
                    {
                        App.proxSocket.Send(App.sendData);
                    }

                    App.XtDisconnectNum = 0;
                    App.XtIsOpen = true;
                }
                else
                {
                    if (App.proxSocket == null)
                    {
                        return;
                    }

                    if (App.proxSocket != null)
                    {
                        if (App.proxSocket.Connected)
                        {
                            App.proxSocket.Shutdown(SocketShutdown.Both);

                            //Shutdown掉Socket后主线程停止10ms，保证Socket的Shutdown完成
                            System.Threading.Thread.Sleep(10);

                            //关闭客户端Socket,清理资源
                            App.proxSocket.Close();
                            App.proxSocket = null;
                        }

                    }

                    if (!App.isMaster.Value)
                    {
                        if (!string.IsNullOrEmpty(App.MasterIP) && !string.IsNullOrEmpty(App.XtIP))
                        {
                            App.XtDisconnectNum += 1;
                            Thread.Sleep(1000);
                        }
                    }
                    App.XtIsOpen = false;
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(ex.Message, "心跳异常");
            }

        }


        /// <summary>
        /// 删除最近一段时间的日志
        /// </summary>
        /// <returns></returns>
        public async Task RemoveLog()
        {
            //var timer=  ConfigurationManager.AppSettings["DeleteLogTime"]?.ToString()??"20";
            //var path= AppDomain.CurrentDomain.BaseDirectory + "Log";

            // DataHelpers.DeleteFile(path,timer.ToInt());
            // DataHelpers.DeleteDirectory(path, timer.ToInt());
        }

    
         
    }
}
